from app.core.logger import logger, TraceID
from app.services.wp_service import query_wp_products
from app.core.task_db import TaskDBSession
from app.crud.waveup.wp_collection import get_collection_by_product_id, create_collection
from app.schemas.waveup.wp_collection import WpCollectionCreate
from app.services.xm_service import search_app_new

async def sync_wp_products():
    """同步WaveUp藏品"""
    TraceID.set()
    logger.info("开始同步WaveUp藏品...")
    # 1. 查询WaveUp藏品信息
    resp = await query_wp_products()
    logger.info(f"查询WaveUp藏品响应: {resp}")
    if resp["rc"] != 0:
        logger.error(f"查询WaveUp藏品失败: {resp}")
        return
    # 2. 解析响应数据
    totalPage = resp["data"]["totalPage"]
    logger.info(f"查询到WaveUp共 {resp['data']['total']} 条藏品, 共 {totalPage} 页")
    products = resp["data"]["records"]
    # 3. 分页查询WaveUp藏品
    for pageNo in range(1, totalPage + 1):
        logger.info(f"开始处理第 {pageNo} 页WaveUp藏品...")
        if pageNo > 1:
            products = await query_wp_products_page(pageNo=pageNo)
        for product in products:
            # 4. 检查藏品是否已存在
            async with TaskDBSession() as db_session:
                collection = await get_collection_by_product_id(
                    session=db_session, product_id=product["productId"]
                )
                if collection:
                    logger.info(f"WaveUp藏品 {product['productId']} 已存在, 跳过")
                    continue
                # 5. 查询XM藏品
                xm_resp = await search_app_new(search_name=(product["productName"]).strip(), page_size=1)
                logger.info(f"查询XM藏品 {product['productName']} 响应: {xm_resp}")
                if xm_resp["code"] != 200:
                    logger.error(f"查询XM藏品 {product['productId']} 失败: {xm_resp}")
                    continue

                # 6. 创建新藏品
                collection_in = WpCollectionCreate(
                    productId=product["productId"],
                    productName=product["productName"],
                    imageUrl=product["imageUrl"],
                    detailUrl=product["detailUrl"],
                    description=product["description"],
                    issueAuthor=product["issueAuthor"] if product["issueAuthor"] else "",
                    issueAmount=product["issueAmount"],
                    archiveId=xm_resp["data"]["archiveList"][0]["archiveId"] if len(xm_resp["data"]["archiveList"]) > 0 else 0
                )
                await create_collection(
                    session=db_session, collection_in=collection_in
                )
                logger.info(f"创建WaveUp藏品 {product['productId']} 成功")
    logger.info("同步WaveUp藏品完成")

async def query_wp_products_page(pageNo: int, pageSize: int = 100):
    """按页码查询WaveUp藏品"""
    # 1. 查询WaveUp藏品信息
    resp = await query_wp_products(pageNo=pageNo, pageSize=pageSize)
    if resp["rc"] != 0:
        logger.error(f"查询WaveUp藏品第 {pageNo} 页失败: {resp}")
        return
    # 2. 解析响应数据
    products = resp["data"]["records"]
    logger.info(f"查询到WaveUp藏品第 {pageNo} 页共 {len(products)} 条: {products}")
    return products
    
